﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using DevExpress.Xpo;


namespace RemoteImaging.LicensePlate
{
    using RemoteImaging.Extensions;

    public class LicensePlateInfo : XPObject
    {
        [NonPersistent]
        public static string ImageStoreRootPath { get; set; }



        static LicensePlateInfo()
        {
            ImageStoreRootPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LicensePlateImages");
        }

        public LicensePlateInfo()
            : base()
        {
        }

        public LicensePlateInfo(Session session)
            : base(session)
        {

        }


        private DateTime _captureTime;
        [System.ComponentModel.DisplayName("抓拍时间")]
        public DateTime CaptureTime
        {
            get { return _captureTime; }
            set { SetPropertyValue("CaptureTime", ref _captureTime, value); }
        }

        private string _licensePlateNumber;
        [System.ComponentModel.DisplayName("车牌号码")]
        public string LicensePlateNumber
        {
            get { return _licensePlateNumber; }
            set { SetPropertyValue("LicensePlateNumber", ref _licensePlateNumber, value); }
        }

        private string _licensePlateColor;
        [System.ComponentModel.DisplayName("车牌颜色")]
        public string LicensePlateColor
        {
            get { return _licensePlateColor; }
            set { SetPropertyValue("LicensePlateColor", ref _licensePlateColor, value); }
        }


        private bool _wrongDirection;
        public bool WrongDirection
        {
            get { return _wrongDirection; }
            set { SetPropertyValue("WrongDirection", ref _wrongDirection, value); }
        }

        private int _capturedFrom;
        public int CapturedFrom
        {
            get { return _capturedFrom; }
            set { SetPropertyValue("CapturedFrom", ref _capturedFrom, value); }
        }

        public int PlateX { get; set; }

        public int PlateY { get; set; }

        public int PlateW { get; set; }

        public int PlateH { get; set; }

        private string _imageRelativePath;
        public string ImageRelativePath
        {
            get { return _imageRelativePath; }
            set { SetPropertyValue("ImageRelativePath", ref _imageRelativePath, value); }
        }


        private Image _image;


        [NonPersistent]
        [Delayed]
        public Image Image
        {
            get { return _image; }
            set { if (value != null) _image = value; }
        }

        [NonPersistent]
        public bool ImageFileExists
        {
            get
            {
                if (string.IsNullOrEmpty(_imageRelativePath))
                {
                    return false;
                }
                return System.IO.File.Exists(AbsoluteImagePath);
            }
        }



        [NonPersistent]
        [Delayed]
        public Image ImageCopy
        {
            get
            {
                Image img = null;
                TryLoadImageCopy(out img);
                System.Diagnostics.Debug.WriteLine("load image " + Oid);

                return img;
            }
        }


        public bool TryLoadImageCopy(out Image image)
        {
            image = null;
            if (File.Exists(AbsoluteImagePath))
            {
                try
                {
                    image = AForge.Imaging.Image.FromFile(AbsoluteImagePath);
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }

            return false;
        }

        public static Bitmap Crop(Bitmap bitmap, Rectangle rect)
        {
            // create new bitmap with desired size and same pixel format
            var croppedBitmap = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat);

            // create Graphics "wrapper" to draw into our new bitmap
            // "using" guarantees a call to gfx.Dispose()
            using (var gfx = Graphics.FromImage(croppedBitmap))
            {
                // draw the wanted part of the original bitmap into the new bitmap
                gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel);
            }

            return croppedBitmap;
        }

        [NonPersistent]
        public string AbsoluteImagePath
        {
            get
            {
                if (string.IsNullOrEmpty(_imageRelativePath))
                {
                    return null;
                }

                var p = System.IO.Path.Combine(ImageStoreRootPath, _imageRelativePath);
                return p;
            }
        }

        protected override void OnSaving()
        {
            base.OnSaving();

            if (_imageRelativePath == null && Image != null)
            {
                var relativePath = GetNewRelativeImagePath();
                var absolutePath = System.IO.Path.Combine(ImageStoreRootPath, relativePath);

                var dir = System.IO.Directory.GetParent(absolutePath).ToString();
                if (!System.IO.Directory.Exists(dir))
                {
                    System.IO.Directory.CreateDirectory(dir);
                }

                this.Image.Save(absolutePath);

                _imageRelativePath = relativePath;
            }
        }

        protected override void OnSaved()
        {
            base.OnSaved();

            if (IsDeleted)
            {
                var path = AbsoluteImagePath;
                if (string.IsNullOrEmpty(path))
                    return;

                Damany.Util.IO.FileHelper.EnsureDelete(path);
            }
        }

        public override void AfterConstruction()
        {
            base.AfterConstruction();
        }


        private string GetNewRelativeImagePath()
        {

            return string.Format(@"{0:d4}{1:d2}{2:d2}\{3}.jpg",
                                            _captureTime.Year,
                                            _captureTime.Month,
                                            _captureTime.Day,
                                            Guid.NewGuid());
        }
    }
}
